<template>
  <div class="category-page">
    <van-nav-bar
      title="商品管理"
      left-arrow
      @click-left="router.back()"
    >
      <template #right>
        <div class="add-button" @click="showAddCategoryPopup">
          <van-icon name="plus" size="18" />
          <span>添加分类</span>
        </div>
      </template>
    </van-nav-bar>

    <!-- 搜索框 -->
    <div class="search-bar">
      <van-search
        v-model="query.categoryName"
        placeholder="请输入分类名称"
        show-action
        @search="onSearch"
        @clear="onClear"
      >
        <template #action>
          <div @click="onSearch(query.categoryName)">搜索</div>
        </template>
      </van-search>
    </div>

    <!-- 分类列表 -->
    <div class="category-list">
      <van-loading v-if="loading" type="spinner" size="24px" vertical />
      <van-empty v-else-if="categories.length === 0" description="暂无分类数据" />
      
      <van-cell-group v-else inset>
        <van-cell 
          v-for="category in categories" 
          :key="category.id"
          :title="category.categoryName"
          :label="`商品数量: ${category.productCount ?? 0}`"
          is-link
          @click="viewProducts(category)"
          class="category-cell"
        >
          <template #right-icon>
            <div class="cell-actions">
              <van-icon 
                name="edit" 
                class="edit-icon" 
                @click.stop="editCategory(category)"
              />
              <van-icon 
                name="delete" 
                class="delete-icon" 
                @click.stop="confirmDelete(category)"
                :class="{'disabled': isProcessing}"
              />
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </div>
    
    <!-- 分页 -->
    <div class="pagination" v-if="categories.length > 0">
      <van-pagination
        v-model="query.current"
        :total-items="pagination.total"
        :items-per-page="query.size"
        force-ellipses
        @change="onPageChange"
      />
    </div>

    <!-- 底部添加按钮 -->
    <div class="bottom-actions">
      <van-button type="primary" block round @click="showAddCategoryPopup">
        添加分类
      </van-button>
    </div>

    <!-- 添加/编辑分类对话框 -->
    <van-dialog
      v-model:show="showCategoryDialog"
      :title="editingCategory ? '编辑分类' : '添加分类'"
      show-cancel-button
      confirm-button-text="保存"
      cancel-button-text="取消"
      :confirm-button-disabled="!categoryForm.categoryName || isProcessing"
      @confirm="saveCategory"
      @cancel="resetForm"
      :loading="isProcessing"
    >
      <div class="dialog-content">
        <van-form>
          <van-field
            v-model="categoryForm.categoryName"
            name="name"
            label="分类名称"
            placeholder="请输入分类名称"
            :rules="[{ required: true, message: '请填写分类名称' }]"
            class="name-field"
          />
        </van-form>
      </div>
    </van-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { 
  getCategoryList, 
  getCategoryPage,
  addCategory, 
  updateCategory, 
  deleteCategory, 
  type Category,
  type CategoryQuery,
  type PageResult
} from '../api/category'

const router = useRouter()
const loading = ref(false)
const isProcessing = ref(false) // 添加处理中状态

// 分类数据
const categories = ref<Category[]>([])

// 查询条件
const query = ref<CategoryQuery>({
  categoryName: '',
  current: 1,
  size: 10
})

// 分页信息
const pagination = ref({
  total: 0,
  current: 1,
  pages: 0
})

// 添加/编辑分类表单
const showCategoryDialog = ref(false)
const editingCategory = ref<Category | null>(null)
const categoryForm = ref({
  categoryName: '',
  description: ''
})

// 加载分类数据
const fetchCategories = async (showLoadingIndicator = true) => {
  if (showLoadingIndicator) {
    loading.value = true
  }
  
  try {
    const result = await getCategoryPage(query.value)
    categories.value = result.records
    pagination.value = {
      total: result.total,
      current: result.current,
      pages: result.pages
    }
  } catch (error) {
    console.error('加载分类数据失败:', error)
    showToast('加载分类数据失败')
  } finally {
    loading.value = false
  }
}

// 页码变化
const onPageChange = (page: number) => {
  query.value.current = page
  fetchCategories()
}

// 清空搜索框
const onClear = () => {
  query.value.categoryName = ''
  query.value.current = 1 // 重置到第一页
  fetchCategories()
}

// 查询关键词变化
const onSearch = (val?: string) => {
  query.value.categoryName = val || ''
  query.value.current = 1 // 重置到第一页
  fetchCategories()
}

// 查看分类下的商品
const viewProducts = (category: Category) => {
  router.push(`/products/${category.id}`)
}

// 编辑分类
const editCategory = (category: Category) => {
  editingCategory.value = category
  categoryForm.value = {
    categoryName: category.categoryName,
    description: category.description || ''
  }
  showCategoryDialog.value = true
}

// 确认删除分类
const confirmDelete = (category: Category) => {
  if (isProcessing.value) return // 如果正在处理中，则不响应点击
  
  showDialog({
    title: '确认删除',
    message: `确定要删除分类"${category.categoryName}"吗？删除后将无法恢复。`,
    showCancelButton: true,
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24'
  }).then(async () => {
    isProcessing.value = true
    
    try {
      // 乐观更新UI
      const tempCategories = [...categories.value]
      categories.value = categories.value.filter(item => item.id !== category.id)
      
      // 执行删除逻辑
      const success = await deleteCategory(category.id)
      
      if (success) {
        showToast({
          type: 'success',
          message: '删除成功',
          position: 'bottom'
        })
      } else {
        // 删除失败，恢复数据
        categories.value = tempCategories
        showToast({
          type: 'fail',
          message: '删除失败',
          position: 'bottom'
        })
      }
    } catch (error) {
      console.error('删除分类失败:', error)
      // 删除失败，重新加载数据
      fetchCategories(false)
    } finally {
      isProcessing.value = false
    }
  }).catch(() => {
    // 取消删除操作
  })
}

// 保存分类
const saveCategory = async () => {
  // 按钮已经禁用，这里不需要再验证表单
  if (!categoryForm.value.categoryName || isProcessing.value) return false
  
  isProcessing.value = true
  
  try {
    if (editingCategory.value) {
      // 编辑现有分类
      const tempCategory = {...editingCategory.value}
      
      // 乐观更新UI
      const index = categories.value.findIndex(c => c.id === editingCategory.value?.id)
      if (index !== -1) {
        const updatedCategory = {
          ...editingCategory.value,
          categoryName: categoryForm.value.categoryName,
          description: categoryForm.value.description
        }
        categories.value[index] = updatedCategory
      }
      
      const success = await updateCategory({
        ...editingCategory.value,
        categoryName: categoryForm.value.categoryName,
        description: categoryForm.value.description
      })
      
      if (!success) {
        // 如果更新失败，恢复原始数据
        const index = categories.value.findIndex(c => c.id === tempCategory.id)
        if (index !== -1) {
          categories.value[index] = tempCategory
        }
        
        showToast({
          type: 'fail',
          message: '更新分类失败',
          position: 'bottom'
        })
      } else {
        showToast({
          type: 'success',
          message: '更新成功',
          position: 'bottom'
        })
      }
    } else {
      // 添加新分类
      const success = await addCategory({
        categoryName: categoryForm.value.categoryName,
        description: categoryForm.value.description
      })
      
      if (success) {
        // 添加成功后，只更新第一页数据
        if (query.value.current === 1) {
          fetchCategories(false)
        } else {
          // 如果当前不在第一页，则切换到第一页查看新添加的分类
          query.value.current = 1
          fetchCategories(false)
        }
        
        showToast({
          type: 'success',
          message: '添加成功',
          position: 'bottom'
        })
      }
    }
    
    // 重置表单
    resetForm()
    return true
  } catch (error) {
    console.error('保存分类失败:', error)
    showToast({
      type: 'fail',
      message: '操作失败，请重试',
      position: 'bottom'
    })
    return false
  } finally {
    isProcessing.value = false
  }
}

// 重置表单
const resetForm = () => {
  editingCategory.value = null
  categoryForm.value = {
    categoryName: '',
    description: ''
  }
}

// 添加分类对话框
const showAddCategoryPopup = () => {
  editingCategory.value = null
  categoryForm.value = {
    categoryName: '',
    description: ''
  }
  showCategoryDialog.value = true
}

onMounted(() => {
  fetchCategories()
})
</script>

<style lang="scss" scoped>
.category-page {
  min-height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;

  .add-button {
    display: flex;
    align-items: center;
    color: #1989fa;
    font-size: 14px;
    
    .van-icon {
      margin-right: 2px;
    }
  }

  .category-list {
    flex: 1;
    padding: 12px;
    padding-bottom: 70px; // 为底部按钮留出空间
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
  }

  .cell-actions {
    display: flex;
    align-items: center;
  }

  .edit-icon,
  .delete-icon {
    font-size: 20px;
    margin-left: 8px;
    color: #969799;
    transition: opacity 0.2s;
  }

  .delete-icon {
    color: #ee0a24;
    
    &.disabled {
      opacity: 0.5;
      pointer-events: none;
    }
  }

  .bottom-actions {
    padding: 16px;
    background: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: center;
    z-index: 10;
  }

  .dialog-content {
    padding: 16px 0;
    
    .name-field {
      :deep(.van-field__control) {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  .search-bar {
    padding: 8px 0;
    background-color: #fff;
  }

  .pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    margin-bottom: 70px;
  }
}

:deep(.van-field__label) {
  width: 70px;
  color: #323233;
}

:deep(.van-dialog__content) {
  padding-top: 8px;
}

:deep(.van-dialog__header) {
  padding: 16px 0;
  font-weight: 500;
  font-size: 16px;
}

.category-cell {
  :deep(.van-cell__title) {
    flex: 3;
    overflow: hidden;
  }
  
  :deep(.van-cell__title span) {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  :deep(.van-cell__value) {
    flex: 2;
    text-align: right;
  }
  
  :deep(.van-cell__label) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  transition: background-color 0.2s;
  
  &:active {
    background-color: #f2f3f5;
  }
}

:deep(.van-cell-group--inset) {
  width: 100%;
  margin: 0;
}

// 添加 fade 过渡效果
.van-cell-group {
  transition: opacity 0.3s;
}
</style> 